<template>
  <div class="top overflow-hidden h-[100%]">
    <el-row :gutter="20">
      <el-col
        :span="6"
        class="border-r-2 h-[calc(100vh-30px)!important] overflow-y-scroll relative"
      >
        <div
          class="w-full flex justify-around h-[50px] border-b-2 cursor-pointer sticky top-0 bg-white"
        >
          <div
            class="w-[50%] text-center leading-[50px]"
            id="openBtns"
            @click="openFiles"
          >
            打开
          </div>
          <div
            class="w-[50%] text-center leading-[50px]"
            id="newBtns"
            @click="addFiles"
          >
            新建
          </div>
        </div>
        <div
          class="w-full h-[8vh] shadow-sm flex justify-around items-center pl-[30px]"
          :class="{ 'bg-[#e7e4e4]': item.path == articlePath }"
          v-for="(item, index) in state.fileList"
          :key="item.path"
          @click="toggleArticle(item)"
        >
          <div class="w-[70%] flex flex-col items-start">
            <span class="text-[20px] flex items-center">
              <span v-if="!item.edit">{{ item.name }}</span>
              <el-input
                :id="`nameInput${index}`"
                v-show="item.edit"
                v-model="item.editName"
                size="default"
                placeholder="Please input"
                @keydown.enter="saveFileName(index)"
              />
              <el-icon
                class="ml-[10px]"
                :size="14"
                v-if="!item.edit"
                @click="editFileName(index)"
              >
                <Edit />
              </el-icon>

              <el-icon
                class="ml-[10px]"
                :size="14"
                v-if="item.edit"
                @click="saveFileName(index)"
                ><Check
              /></el-icon>
            </span>
            <span class="text-[#ccc]" v-show="item.path"
              >路径：{{ item.path }}</span
            >
          </div>
          <el-button
            type="primary"
            size="small"
            round
            @click="toggleArticle(item)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            round
            @click="deleteFiles(item.path, index)"
            >删除</el-button
          >
          <el-button
            type="danger"
            size="small"
            round
            v-if="item.isNew && item.edit"
            @click.stop="cancel(index)"
            >取消</el-button
          >
        </div>
      </el-col>
      <el-col id="editorCont" :span="18" class="h-[calc(100vh-30px)!important]">
        <MdEditor
          ref="mdEditor"
          :articlePath="articlePath"
          @saves="savesNew"
          :disabled="isDisabledEdit"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import MdEditor from "@renderer/components/mdEditor/index.vue";
import { onMounted, ref, reactive, nextTick, computed } from "vue";
import { useDriver } from "@renderer/utils/driver";
import "driver.js/dist/driver.css";
const { ipcRenderer } = window;
let articlePath = ref("");
let mdEditor = ref(null);
let state = reactive({
  fileList: [],
});
const { mydriver } = useDriver();
onMounted(() => {
  initFileList();

  setTimeout(() => {
    mydriver.value.drive();
  }, 1000);
});
const cancel = (index) => {
  articlePath.value = state.fileList[0].path;
  state.fileList.splice(index, 1);
};
const toggleArticle = (item) => {
  if (editIngNow.value && item.path) {
    ElMessage.warning("还未保存新文件");
    return;
  }
  articlePath.value = item.path;
};
const editIngNow = computed(() => {
  return articlePath.value == "";
});
const isDisabledEdit = computed(() => {
  let flag = state.fileList.length == 0;
  if (flag) {
    nextTick(() => {
      mdEditor.value.clearValue();
    });
  }
  return flag;
});
const initFileList = () => {
  let res = ipcRenderer.sendSync("getStore", "fileList");
  if (res) {
    state.fileList = JSON.parse(res);
    articlePath.value = state.fileList[0]?.path || "";
  } else {
    state.fileList = [];
  }
};
const editFileName = (i: number) => {
  state.fileList[i].editName = state.fileList[i].name;
  state.fileList[i].edit = true;
  nextTick(() => {
    let refInput: HTMLInputElement = document.querySelector(`#nameInput${i}`);
    refInput.focus();
  });
};
const saveFileName = async (i: number) => {
  if (state.fileList[i].isNew) {
    saveNewFileName(i);
    return;
  }
  let newPath = state.fileList[i].path
    .split(state.fileList[i].name)
    .join(state.fileList[i].editName);
  state.fileList[i].name = state.fileList[i].editName;
  state.fileList[i].edit = false;

  let res = await ipcRenderer.invoke("reNameFile", {
    oldPath: state.fileList[i].path,
    newPath: newPath,
  });
  if (res) {
    state.fileList[i].path = newPath;
    delete state.fileList[i].edit;
    delete state.fileList[i].editName;
    let flag = ipcRenderer.sendSync("setStore", {
      key: "fileList",
      value: JSON.stringify([...state.fileList]),
    });
    if (flag) {
      initFileList();
      ElMessage.success("重命名成功");
    }
  }
};
const saveNewFileName = (i: number) => {
  if (state.fileList[i].editName.indexOf(".md") > -1) {
    state.fileList[i].name = state.fileList[i].editName;
  } else {
    state.fileList[i].name = state.fileList[i].editName + ".md";
  }
  state.fileList[i].edit = false;
  articlePath.value = state.fileList[i].path;
};
const openFiles = async () => {
  let res = await ipcRenderer.invoke("openDialog");

  if (!res) return;
  let i = state.fileList.findIndex((it) => it.path == res.path);
  if (i >= 0) {
    ElMessage("文件已经打开");

    return;
  }
  let flag = ipcRenderer.sendSync("setStore", {
    key: "fileList",
    value: JSON.stringify([...state.fileList, res]),
  });
  if (flag) {
    state.fileList = JSON.parse(ipcRenderer.sendSync("getStore", "fileList"));

    articlePath.value = res.path;
  }
};

const deleteFiles = (path: string, i: number) => {
  ElMessageBox.confirm("确定要删除吗?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let i = state.fileList.findIndex((it) => it.path == path);

      state.fileList.splice(i, 1);

      let flag = ipcRenderer.sendSync("setStore", {
        key: "fileList",
        value: JSON.stringify([...state.fileList]),
      });
      if (flag) {
        initFileList();
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

const addFiles = () => {
  state.fileList.push({
    name: "",
    path: "",
    edit: true,
    editName: "",
    isNew: true,
  });
  nextTick(() => {
    articlePath.value = "";
    let refInput: HTMLInputElement = document.querySelector(
      `#nameInput${state.fileList.length - 1}`
    );
    refInput.focus();
  });
};

const savesNew = async (value) => {
  console.log("value", value);

  let filePath = await ipcRenderer.invoke("openSaveDialog", {
    file: value,
    title: state.fileList[state.fileList.length - 1].name,
  });
  if (filePath) {
    ElMessage.success("保存成功");
    delete state.fileList[state.fileList.length - 1].isNew;
    delete state.fileList[state.fileList.length - 1].edit;
    delete state.fileList[state.fileList.length - 1].editName;
    state.fileList[state.fileList.length - 1].path = filePath;
    let flag = ipcRenderer.sendSync("setStore", {
      key: "fileList",
      value: JSON.stringify([...state.fileList]),
    });
    if (flag) {
      initFileList();
      articlePath.value = filePath;
      ElMessage.success("保存成功");
    }
  } else {
    ElMessage.success("保存失败");
  }
};
</script>

<style scoped lang="scss">
.top {
  padding-top: 30px;
}
</style>
